<?php

class WxVote extends AppModel {

    var $name = 'WxVote';
    
    var $msg_content  = '';
    
    var $content_to_oss = true; //将内容保存到OSS
    var $delete_id = 0;
    
    public function beforeSave($options = array())
    {
    	parent::beforeSave($options);
    	
    	$this->msg_content = $this->data['WxVote']['content'];
    	unset($this->data['WxVote']['content']);
    	return true;
    }
    
    public function afterSave($created = false) {
    	parent::afterSave($created);
    	
    	$id =  $this->id;
    	if( $this->content_to_oss && $id && $this->msg_content ){
	    	App::uses('CrawlUtility', 'Utility');
	    	if(! CrawlUtility::saveToAliOss($this->msg_content, '/WxVote/'.$id,false,true)) {
	    		$this->updateAll(array('content'=> $this->escape_string($this->msg_content)),array('id' => $id) );
	    		// 保存失败时，将内容回写到数据库。
	    	}
    	}
    	return true;
    }
    
    public function beforeDelete($cascade = true) {
    	parent::beforeDelete($cascade);
    	$this->delete_id = $this->id;    	
    }
    
    public function afterDelete(){
    	if( $this->content_to_oss && $this->delete_id ){
    		App::uses('CrawlUtility', 'Utility');
    		$object_name = '/WxVote/'. $this->delete_id;
    		if(! CrawlUtility::delFromAliOss( $object_name )) {
    			// 删除数据后，删除OSS中存储的内容
    			CakeLog::info("delete from oss $object_name  failed");
    		}
    	}
    	parent::afterDelete();
    }
    
    public function afterFind($results, $primary = false) {
    	
    	if( $this->content_to_oss ) {
	    	App::uses('CrawlUtility', 'Utility');
	    	try{
		    	foreach($results as &$msg) {
		    		$content = CrawlUtility::getFromAliOss('/WxVote/'.$msg['WxVote']['id']);
		    		if($content) {
		    			$msg['WxVote']['content'] = $content; // 有内容时，才使用值，否则使用数据库中的值。兼容数据库中已有的数据
		    		}
		    	}
	    	}
	    	catch(Exception $e){
	    		return $results;
	    	}
    	}
    	return $results;
    }
    
}
?>